# -- coding: utf-8 --
# @Time : 2022/4/5 22:32
# @Author : 曹庭
# @Email : caoting0403@163.com
# @File : label.py
# @Software: PyCharm

from . import api
from course.utils.commons import login_required
from flask import g, current_app, jsonify, request
from course.utils.response_code import RET
from course.utils.image_storage import storage
from course.models import Label
from course import db, constants
from sqlalchemy.exc import IntegrityError


@api.route("/add_label", methods=["POST"])
@login_required
def add_label():
    """
    新增标签
    参数：标签名称
    :return:
    """
    user_id = g.user_id

    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    request_dict = request.get_json()
    label_name = request_dict.get("label_name")

    # 校验参数
    if not all([label_name]):
        return jsonify(errno=RET.PARAMERR, errmag="参数不完整")

    # 保存用户的注册信息到数据库中
    label = Label(label_name=label_name)
    try:
        db.session.add(label)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        # 表示用户名和邮箱有重复值
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库异常")

    # 返回结果
    return jsonify(errno=RET.OK, errmsg="新增标签成功")


@api.route("/edit_label", methods=["POST"])
@login_required
def edit_label():
    """
    修改标签
    参数：标签编号，标签名称
    :return:
    """
    # 判断用户权限
    user_id = g.user_id
    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    request_dict = request.get_json()
    label_id = request_dict.get("label_id")
    label_name = request_dict.get("label_name")

    # 校验参数
    if not all([label_id, label_name]):
        return jsonify(errno=RET.PARAMERR, errmag="参数不完整")

    try:
        Label.query.filter_by(id=label_id).update({"label_name": label_name})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="标签修改失败")

    # 返回结果
    return jsonify(errno=RET.OK, errmsg="标签修改成功")


@api.route("/del_label", methods=["POST"])
@login_required
def del_label():
    """
    删除类目
    参数：类目编号
    :return:
    """

    # 判断用户权限
    user_id = g.user_id
    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    request_dict = request.get_json()
    label_id = request_dict.get("label_id")

    # 校验参数
    if not all([label_id]):
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    try:
        content = Label.query.filter_by(id=label_id).first()
        db.session.delete(content)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="目录删除失败")

    # 返回结果
    return jsonify(code=RET.OK, msg="删除成功")


@api.route("/label_list", methods=["POST"])
@login_required
def get_label_list():
    """
    标签列表数据查询
    :return:
    """
    # # 判断用户权限
    # user_id = g.user_id
    # if user_id != 1:
    #     return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    req_dict = request.get_json()
    curr = req_dict.get("curr")
    nums = req_dict.get("nums")
    searchParams = req_dict.get("searchParams")
    print(searchParams)

    label_name = searchParams["label_name"]

    print(label_name)

    if label_name == "":
        try:
            paginate = Label.query.paginate(page=curr, per_page=nums)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="数据库查询失败")

        label_list = []

        labels = paginate.items
        total = paginate.total

        for label in labels:
            label_dict = label.to_dict()
            label_list.append(label_dict)
            print(label_dict)
        print(label_list)

        # 返回结果
        return jsonify(code=RET.OK, count=total, msg="", data=label_list)

    try:
        paginate = Label.query.filter(Label.label_name.like('%{}%'.format(label_name))).paginate(page=curr, per_page=nums)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")

    label_list = []
    labels = paginate.items
    total = paginate.total

    for label in labels:
        label_dict = label.to_dict()
        label_list.append(label_dict)
        print(label_dict)
    print(label_list)

    # 返回结果
    return jsonify(code=RET.OK, count=total, msg="", data=label_list)


@api.route("/get_labels_all_list", methods=["POST"])
# @login_required
def get_labels_all_list():
    """
    获取所有标签信息
    :return:
    """

    try:
        labels = Label.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")

    label_list = []

    for label in labels:
        label_dict = label.to_dict()
        label_list.append(label_dict)
        print(label_dict)
    print(label_list)

    # 返回结果
    return jsonify(code=RET.OK, msg="", data=label_list)
